# -*- coding:utf-8 -*-
from tornado import gen
import hashlib, json


from appcommon.framework import WebBaseHandler
from common import utiltool
import tools
import settings
from common import config
import models



class LoginHandler(WebBaseHandler):
    """
    登录
    """
    # @decorator.check_params(['product_type', 'class_id', 'site_id'])
    # @decorator.verify_params
    @gen.coroutine
    def get(self):
        if self.current_user:
            self.redirect('/')
        else:
            self.render('login.html', code='0')

    @gen.coroutine
    def post(self):
        user_name = self.get_argument('username', '')
        password = self.get_argument('pwd', '')
        pwdtmp = hashlib.md5()
        pwdtmp.update(password)
        md5pwd = pwdtmp.hexdigest()
        auth = yield tools.authenticate(user_name, md5pwd)
        if auth:
            self.set_secure_cookie("user_name", user_name, 1)
            self.set_secure_cookie("access_token", '0', 1)
            utiltool.response_write(self, {'code': '0', 'msg': u'success'})

        else:
            utiltool.response_write(self, {'code': '1004', 'msg': u'用户名或密码输入有误，请确认'})


class LogoutHandler(WebBaseHandler):
    """
    登出
    """
    # @decorator.check_params(['product_type', 'class_id', 'site_id'])
    # @decorator.verify_params
    @gen.coroutine
    def post(self):
        user = self.current_user
        if user:
            self.clear_cookie('user_name')
            self.clear_cookie('access_token')
            utiltool.response_write(self, {'code': '0'})
        else:
            utiltool.response_write(self, {'code': '1'})


class IndexHandler(WebBaseHandler):
    """
    首页
    """
    # @decorator.check_params(['product_type', 'class_id', 'site_id'])
    # @decorator.verify_params
    @gen.coroutine
    def get(self):
        if self.current_user:
            menu_list = yield models.get_menu_tree()
            menu_list.append(dict(
                menu_name=u"菜单管理",
                link_list=[{'link_name': u"菜单管理", 'link': '/menu_manage.html'}]
            ))
            self.render('index.html', menu_list=menu_list, user_name=self.current_user['user_name'])
        else:
            self.render('login.html', code='0')


class MenuManageHandler(WebBaseHandler):
    """
    菜单管理
    """
    # @decorator.check_params(['product_type', 'class_id', 'site_id'])
    # @decorator.verify_params
    @gen.coroutine
    def get(self):
        menu_type = self.get_argument('menu_type', '0')
        parent_id = self.get_argument('parent_id', '-1')
        left = self.get_argument('left', '')
        menu_list = yield models.get_manage_menu(menu_type, parent_id, left)
        utiltool.response_write(self, menu_list)


class UpdateMenuHandler(WebBaseHandler):
    """
    菜单管理
    """
    @gen.coroutine
    def post(self, ex=None):
        dic = self.request.arguments
        for k in dic.iterkeys():
            dic[k] = dic[k][0]
        try:
            yield models.update_manage_menu(dic)
            res = {'code': '0', 'msg': u'保存成功'}
        except ex:
            res = {'code': '1', 'msg': u'保存失败'}
        utiltool.response_write(self, res)


class DelMenuHandler(WebBaseHandler):
    """
    菜单管理
    """
    @gen.coroutine
    def post(self, ex=None):
        menu_id = self.get_argument('menu_id', '')
        try:
            yield models.del_manage_menu(menu_id)
            res = {'code': '0', 'msg': u'删除成功'}
        except ex:
            res = {'code': '1', 'msg': u'删除失败'}
        utiltool.response_write(self, res)
